using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField] public float Power;
    private float maxTimer = 2f;

    private float timer = 0f;

    private Rigidbody mRigidbody;
    private bool doJump = false;
    private bool isGround = true;

    void Start()
    {
        mRigidbody = this.GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (Input.GetMouseButton(0) && timer <= maxTimer)
        {
            timer += Time.deltaTime;
            var yScale = 0.5f + 0.5f * (maxTimer - timer)/maxTimer;
            var xScale = 1f + 0.25f * (timer)/maxTimer;
            transform.localScale = new Vector3(xScale, yScale, xScale);
        }

        if (Input.GetMouseButtonUp(0))
        {
            transform.localScale = Vector3.one;
            doJump = true;
        }
    }
    
    void FixedUpdate()
    {
        if (doJump && isGround)
        {
            Jump();
            doJump = false;
            isGround = false;
            timer = 0;
        }
        mRigidbody.AddForce(Vector3.down * 50);
    }

    private void Jump()
    {
        Vector3 dir = PlaneManager.Instance.playerAxisX ? Vector3.forward : Vector3.left;
        dir.y = 3;
        mRigidbody.velocity = dir * timer * Power;
    }

    public void OnCollisionEnter(Collision collider)
    {
        if (collider.collider.CompareTag("Ground"))
        {
            PlaneManager.Instance.GenerateGround();
            isGround = true;
            mRigidbody.velocity = Vector3.zero;
            transform.rotation = Quaternion.identity;
        }
    }
}
